use model_graph_channel::{
    cli_request as remote_cli_request,
    data_channels::proxy::{batch_script_request, local_execute_batch_script_request},
    local_execute_cli_request,
};
use model_graph_types::{
    assistant::{
        chat::{ChatMessage, ChatOptions, ChatProvider},
        shell::{
            BatchScriptRequestMessage, ShellRequestMessage, ShellRequestOptions,
            ShellResponseMessage,
        },
    },
    channel::{BatchScriptRequest, CliRequest, HttpRequest, HttpResponse},
    peer::{get_peer_id, is_self},
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

pub async fn shell_request(
    provider: ChatProvider,
    request: ShellRequestMessage,
    options: ShellRequestOptions,
) -> anyhow::Result<ShellResponseMessage> {
    tracing::debug!("请求SHELL接口:{:?}", provider);

    let ShellRequestMessage {
        env,
        current,
        before,
        script,
        after,
    } = request;

    //before

    //script
    let mut peer_id = String::new();
    let is_local = if let Some(peer) = &provider.peer {
        peer_id = peer.clone();
        is_self(peer)?
    } else {
        true
    };

    let cli_request = CliRequest::commands(script)?;

    //
    let response = if is_local {
        tracing::debug!("从本地调用节点SHELL服务:{:?}", cli_request);
        //
        local_execute_cli_request(cli_request).await?
    } else {
        tracing::debug!("调用节点SHELL服务:{}", peer_id);

        remote_cli_request(&peer_id, cli_request, 60000).await?
    };

    //after

    tracing::debug!("调用SHELL服务完成!{:?}", response);
    return Ok(ShellResponseMessage::new()?);
}

pub async fn shell_batch_script_request(
    provider: ChatProvider,
    request: BatchScriptRequestMessage,
    options: ShellRequestOptions,
) -> anyhow::Result<ShellResponseMessage> {
    tracing::debug!("请求SHELL接口:{:?}", provider);

    let BatchScriptRequestMessage {
        env,
        current,
        before,
        script,
        after,
    } = request;

    //before

    //script
    let mut peer_id = String::new();
    let is_local = if let Some(peer) = &provider.peer {
        peer_id = peer.clone();
        is_self(peer)?
    } else {
        true
    };

    let cli_request = BatchScriptRequest::new(script)?;

    //
    let response = if is_local {
        tracing::debug!("从本地调用节点SHELL服务:{:?}", cli_request);
        //
        local_execute_batch_script_request(cli_request).await?
    } else {
        tracing::debug!("调用节点SHELL服务:{}", peer_id);
        batch_script_request(&peer_id, cli_request, 60000).await?
    };

    //after
    tracing::debug!("调用SHELL服务完成!{:?}", response);
    return Ok(ShellResponseMessage::new()?);
}
